<?php
/**
 * 会员模型实体类
 * @author tangbl
 * 
 */
class MemberModel extends Model {
	
	/*array(
		0.字段名   
		1.验证规则 [require 字段必须、email 邮箱、url URL地址、currency 货币、number 数字]
		2.提示信息  {%usr_form_validata_email_email}多国语言
		3.验证条件 [0.(默认)存在字段就验证;1.必须验证;2.值不为空的时候验证]
		4.附加规则 [regex、function、callback、confirm、equal、in、length、between、expire、ip_allow、ip_deny、unique]
		5.验证时   [1.新增数据时候验证;2.编辑数据时候验证;3.(默认)全部情况下验证]
	);*/
	protected $_validate    =   array(
		//array('username','','{%mb_model_ele_username2}',1,'unique',1),
		array('password','require','{%mb_model_ele_password1}',1,'',1),
		array('password','/^.{6,16}$/','{%mb_model_ele_password2}',1,'regex',1),
	);
	
	/*array(
	    0.填充字段:字段名
		1.填充规则:方法名或者字段名
		2.填充时间:[1.新增数据时候验证;2.编辑数据时候验证;3.(默认)全部情况下验证]
		4.附加规则 [function、callback、field 、string ]
	);*/
	protected $_auto    =   array(
		array('addtime','time',1,'function'),
		//array('mobile','username',1,'field'),
		array('password','myencrypt',1,'function'),
		array('solevar','create_id',1,'function')
	);
	
	/**
	 * 保存登陆用户的Session信息
	 * @param $user 用户数组
	 */
	public function setLoginSession($user){

		$model = $this->getMemberSession($user['id']);
		session(C('USER_AUTH_MODEL') ,$model);
		session(C('USER_AUTH_ACCOUNT') ,$user['username']);
		session(C('USER_AUTH_IDEN') ,$user['id']);
		session(C('USER_AUTH_KEY')  ,$user['id']);
		session(C('USER_AUTH_TYPE') ,C('USER_AUTH_MODEL'));
		session(C('USER_AUTH_TRACK'),$user['visitid']);
		
		$mobile = substr_replace($user['username'],'****',-4);
		session("mobile",$mobile);
		cookie("memberName", $user['username'] ,C("COOKIE_KEEP_TIME")*30);
		cookie("memberGuestId", $user['visitid'] ,C("COOKIE_KEEP_TIME"));
	}
	
	/**
	 * seesion需要保存的字段
	 */
	public function getMemberSession($id){
		
		$model = D("MemberInfoView");
		$field = "login_times,last_login_ip,last_login_time,nickname,realname,headpic";
		$rows  = $model->field($field)->find($id);
		//echo $model->getLastSql();dump($rows);exit();
		return $rows;
	}
	
	/**
	 * 会员修改资料后，更新session信息
	 * @param array $user
	 */
	public function setMemberSession($id){
		
		$user = $this->getMemberSession($id);
		session(C('USER_AUTH_MODEL') ,$user);
	}
	
	/**
	 * 清空登陆用户的Session信息
	 */
	public function clearLoginSession(){
	
		unset($_SESSION[C('USER_AUTH_MODEL')]);
		unset($_SESSION[C('USER_AUTH_ACCOUNT')]);
		unset($_SESSION[C('USER_AUTH_IDEN')]);
		unset($_SESSION[C('USER_AUTH_KEY')]);
		unset($_SESSION[C('USER_AUTH_NAME')]);
		unset($_SESSION[C('USER_AUTH_TYPE')]);
		unset($_SESSION[C('WECHAT_AUTH_IDEN')]);
		unset($_SESSION[C('WECHAT_AUTH_MODEL')]);
		unset($_SESSION[C('USER_AUTH_TRACK')]);
		unset($_SESSION["mobile"]);
		//unset($_SESSION);
		//session_destroy();
	}
	
	/**
	 * 生成用户分享编号(visitid)
	 */
	public function getVisitid(){
	
		$guestid = cookie("memberGuestId");
	
		if(empty($guestid)){
			$guestid = create_id("G");
		}else{
			$m['visitid'] = $guestid ;
			$userid = $this->where($m)->getField("id");
			if($userid){
				$guestid = create_id("G");
			}
		}
		return $guestid;
	}
	
	/**
	 * 保存用户登录的信息(IP和登陆时间)
	 * @param $user array 用户数组
	 */
	public function setLoginDetail($user){
	
		$ip	  =	get_client_ip();
		$data = array();
		if($ip){
			import('ORG.Net.IpLocation');
			$Ip = new IpLocation();
			$location = $Ip->getlocation($ip);
			$data['last_location'] = '';
			if($location['country'] && $location['country']!='CZ88.NET') $data['lastLocation'].=$location['country'];
			if($location['area']    && $location['area']!='CZ88.NET') $data['lastLocation'].=' '.$location['area'];
		}
		$data['id']	= $user['id'];
		$data['last_login_time'] =	time();
		$data['last_login_ip']	 =	get_client_ip();
		$data['login_times']	 =	$user['login_times']+1;
		$this->save($data);
	}
	
	/**
	 * 购物车和收藏夹从游客状态转到会员状态
	 * @param $user array 用户数组
	 */
	public function changUserStatus($user){
		
		if(!C("CART_TO_USER"))return;
		//改变购物车中会员信息和状态
		$userid = session(C('USER_AUTH_KEY'));
		if(empty($userid)){
			$data['userid'] = cookie("memberGuestId");
			$data['type']   = "Guest";
			if($data['userid']){
				$flag = true;
			}
		}else{
			$data['userid'] = $userid;
			$data['type']   = session(C('USER_AUTH_TYPE'));
			if($data['type'] == "MemberWechat"){
				$flag = true;
			}
		}
		
		if($flag){
			//转移购物车
			$map['userid']  = $data['userid'];
			$map['type']    = $data['type'];
			$map['nUserid'] = $user['id'];
			$map['nType']   = "Member";
			//dump($map);exit();
			$json = sendRest("RMS/Cart/changeStatus",$map);
			//echo createRestUrl("RMS/Cart/changeStatus", $map);
		}
	}
	/**
	 * 购物车和收藏夹从游客状态转到会员状态
	 * @param $user array 用户数组
	 */
	public function formGuestCartToUser($user){
		
		if(!C("CART_TO_USER"))return;
		
		//转移Guest和微信会员的购物车
		$userid = session(C('USER_AUTH_KEY'));
		$flag   = false;
		if(empty($userid)){
			$data['userid'] = cookie("memberGuestId");
			$data['type']   = "Guest";
			if($data['userid']){
				$flag = true;
				
			}
		}else{
			$data['userid'] = $userid;
			$data['type']   = session(C('USER_AUTH_TYPE'));
			if($data['type'] == "MemberWechat"){
				$flag = true;
			}
		}
		
		if($flag){
			//转移购物车
			$cart = M("MemberCart");
			$ids  = $cart->where($data)->field("id,pid")->select();
			
			$map['userid'] = $user['id'];
			$eid   = $cart->where($map)->getField("pid" , true);
			foreach($ids as $k=>$v){
				if(!in_array($v["pid"], $eid)){
					$lists[] = $v["id"];
				}
			}
			
			if(count($lists)){

				$rows = array("userid"=>$user['id'],"type"=>"Member");
				$where['id']  = array('in',$lists);
				$res  = $cart->where($where)->save($rows);
			}
			
			//转移收藏夹
			$coll = M("MemberCollect");
			$ids  = $coll->where($data)->field("id,pid")->select();
				
			$eid  = $coll->where($map)->getField("pid" , true);
			foreach($ids as $k=>$v){
				if(!in_array($v["pid"], $eid)){
					$lists[] = $v["id"];
				}
			}
				
			if(count($lists)){
				$rows = array("userid"=>$user['id'],"type"=>"Member");
				$where['id']  = array('in',$lists);
				$res  = $coll->where($where)->save($rows);
			}
		}
	}
	
	/** 
	 * 计算用户个人资料完整度
	 * @param $user array 用户数组
	 * return int integrity
	 */
	public function calcIntegrity($user){
		
		$num = 100;
		if(empty($user['realname'])) $num = $num-20;
		if(empty($user['sex']))      $num = $num-20;
		if(empty($user['mobile']))   $num = $num-20;
		if(empty($user['email']))    $num = $num-20;
		if(empty($user['headpic']))  $num = $num-20;
		return $num;
	}
	
	/**
	 * 用户查询认证
	 * @param $map array 查询数组
	 */
	public function authenticate($map) {
		
        return $this->where($map)->find();
    }
	
	/**
	 * 判断用户名是否存在
	 * @param $map array 查询数组
	 */
	public function validateUsername($map){
		return $this->where($map)->find();
	}
	
	/**
	 * 修改用户密码
	 */
	public function editUserPassword($userid){

		$oldpassword = myencrypt(I("param.oldpassword"));
		$newpassword = myencrypt(I("param.newpassword"));
		
		$map['password'] = $oldpassword;
		$map['id']       = $userid;
		$authInfo        = $this->authenticate($map);
		
		if(false == $authInfo) {
			$flag = false;
		}else{
			$data['id']		  =	$authInfo['id'];
			$data['password'] = $newpassword;
			$flag = $this->save($data);
		}
		return $flag;
	}
	
	/**
	 * 获取用户可以使用的优惠卷列表
	 * @param $userid int 用户编号
	 */
	function getUserCoupon(){
		$userid = session(C('USER_AUTH_KEY'));
		
		$map['userid'] = $userid;
		$map['status'] = 2;
		$map['expires']= time();
		$map['act']    = 1;
		
		$json = sendRest("Coupon/select",$map);
		return $json['data'];
	}
	
	/**
	 * 获取用户可以使用的会员卡
	 * @param $userid int 用户编号
	 */
	function getUserVip(){
		$userid = session(C('USER_AUTH_KEY'));
		
		$map['userid'] = $userid;
		$json = sendRest("Vip/view",$map);
	
		return $json['data'];
	}
	
	/**
	 * 删除旧会员数据
	 */
	public function delOldMember($username){
	
		$map["username"] = $username;
		$map["isactive"] = 2;
	
		return $this->where($map)->delete();
	}
	
	/**
	 * 激活帐号
	 * 保存会员详细信息
	 */
	public function activeSave($user,$field){
		
		$data['id']       = $user['id'];
		$data['isactive'] = 1;
		$data[$field]     = 1;
		$this->save($data);
		
		$user['userid'] = $user['id'];
		$model = M("MemberInfo");
		
		$rows = $model->where(array("username"=>$user['username']))->find();
		
		if($rows['id']){
			$user['id'] = $rows['id'];
			$model->save($user);
		}else{
			unset($user['id']);
			$user['solevar'] = create_id();
			$model->add($user);
		}
	}
	
}
?>